package com.fesine.ssh.dao.impl;

import com.fesine.ssh.dao.SequenceDao;
import com.fesine.ssh.model.Sequence;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 *
 * Created by Fesine on 2016/2/18.
 */
@Repository("sequenceDao")
public class SequenceDaoImpl implements SequenceDao {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    public Sequence load(String id) {
        return (Sequence)this.getCurrentSession().load(Sequence.class,id);
    }

    @Override
    public Sequence get(String id) {
        return (Sequence) this.getCurrentSession().get(Sequence.class, id);
    }

    @Override
    public List<Sequence> findAll() {
        String hql = String.format("from Sequence");
        Query query = this.getCurrentSession().createQuery(hql);
        List<Sequence> sequenceList = query.list();
        return sequenceList;
    }

    @Override
    public List<Sequence> findAll(int offset, int pageSize) {
        String hql =String.format("from Sequence");
        Query query = this.getCurrentSession().createQuery(hql);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List<Sequence> sequenceList = query.list();
        return sequenceList;
    }


    @Override
    public List<Sequence> findByEntity(Sequence entity) {
        return null;
    }

    @Override
    public List<Sequence> findByEntity(Sequence entity, int offset, int pageSize) {
        return null;
    }


    @Override
    public void persist(Sequence entity) {

    }

    @Override
    public String save(Sequence entity) {
        return (String) this.getCurrentSession().save(entity);
    }

    @Override
    public void update(Sequence entity) {
        this.getCurrentSession().update(entity);
    }

    @Override
    public void saveOrUpdate(Sequence entity) {
        this.getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(String id) {
        this.getCurrentSession().delete(id);
    }

    @Override
    public void flush() {

    }

    @Override
    public Sequence getSeq(String name) {
        String hql = String.format("from Sequence where name='%s'", name);
        List<Sequence> list = this.getCurrentSession()
                .createQuery(hql).setCacheable(true).list();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

}
